package com.example.waimai.ui.dashboard;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.baidu.mapapi.model.LatLng;

import com.example.waimai.HttpUtil.MyPost;
import com.example.waimai.MainActivity;
import com.example.waimai.pojo.Food;
import com.example.waimai.pojo.Orders;
import com.example.waimai.util.MyDistanceUtil;
import com.example.waimai.util.MyThreadPool;
import com.example.waimaiandroid.OrderDetailActivity.OrderDetailActivity;
import com.example.waimaiandroid.R;
import com.example.waimaiandroid.comment.Comment;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class orderItemDashAdapter extends BaseAdapter {

    Handler handler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what){

                case 2:
                    // 跳转到订单详细页面
                    requestCertificate((Bundle) msg.obj);
                    break;
                case 3:
                    // 更新成功
                    ViewHolder vh = (ViewHolder) msg.obj;
                    vh.noti_ack.setVisibility(View.GONE);
                    vh.noti_pinjia.setVisibility(View.VISIBLE);
                    Toast.makeText(MainActivity.getMainActivity(),"确认送达！",Toast.LENGTH_SHORT).show();
                    break;
                case 4:
                    // 更新失败
                    Toast.makeText(MainActivity.getMainActivity(),"确认失败，请重试！",Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    private void requestCertificate(Bundle bundle){
        Intent intent = new Intent();
        intent.setComponent(new ComponentName(context, OrderDetailActivity.class));
        intent.putExtras(bundle);
        ((Activity) context).startActivity(intent);
    }

    private Context context;

    private static List<Orders> data = new ArrayList<>();

    public orderItemDashAdapter(List<Orders> data, Context context){
        this.data = data;
        this.context = context;
    }

    private static View view;

    public void updateAll(List<Orders> data){
        this.data = data;
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {

        return data == null ? 0:data.size();
    }



    @Override
    public Object getItem(int position) {
        return data == null ? null : data.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder vh = null;
        if(convertView == null){
            convertView = View.inflate(parent.getContext(), R.layout.order_item_dashboard,null);
            vh = new ViewHolder(convertView);
            convertView.setTag(vh);
        }else{
            vh = (ViewHolder) convertView.getTag();
        }

        /*
        *  TextView noti_orderId;
        TextView noti_storeName;
        TextView noti_orderStartTime;
        TextView Da_orderEndTime;
        TextView noti_remark;
        TextView noti_totalPrice;
        Button noti_detail;
        Button noti_pinjia;
        * */
        // 设置数据
        Orders order = data.get(position);
        vh.noti_orderStartTime.setText(order.getStartTime().toString());
        vh.noti_remark.setText(order.getRemark());
        vh.noti_totalPrice.setText(String.valueOf(order.getTotalPrice()));
       /* vh.noti_orderId.setText(String.valueOf(order.getId()));*/
        vh.noti_storeName.setText(order.getStore().getStoreName());
        if(order.getEndTime() != null)
            vh.Da_orderEndTime.setText(order.getEndTime().toString());

        // 设置一下订单的状态

        setOrderStatus(vh,order,position);

        // 查看详细订单  按钮 监听函数
        vh.noti_detail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MyThreadPool.doJob(new Runnable() {
                    @Override
                    public void run() {
                        Message msg = new Message();
                        msg.what = 2;
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("order",order);
                        msg.obj = bundle;
                        handler.sendMessage(msg);
                    }
                });
            }
        });
        // 设置监听器 评价动作
        vh.noti_pinjia.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 跳转到 评价页面
                Bundle bundle = new Bundle();
                bundle.putSerializable("order",order);
                Intent intent = new Intent();
                intent.setComponent(new ComponentName(MainActivity.getMainActivity(), Comment.class));
                intent.putExtras(bundle);
                intent.putExtra("position",position);
                MainActivity.getMainActivity().startActivityForResult(intent,0);
            }
        });

        // 确认送达的动作
        ViewHolder finalVh = vh;
        vh.noti_ack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Message msg = new Message();
                String url = "updateOrderUserStatus";
                MyThreadPool.doJob(new Runnable() {
                    @Override
                    public void run() {
                        Map<String,Integer> param = new HashMap<>();
                        param.put("orderId",order.getId());
                        param.put("userStatus",2);
                        Boolean update = (Boolean) MyPost.doPost(url,param);
                        if(update){
                            order.setUserStatus(2);
                            msg.what = 3;
                            msg.obj = finalVh;
                        }else{
                            // 更新失败
                            msg.what = 4;
                        }
                        handler.sendMessage(msg);
                    }
                });
            }
        });

        return convertView;
    }

    private void setOrderStatus(ViewHolder vh,Orders order,int position){
        // 首先判断商家的状态
        int status = order.getStoreStatus();
        int userStatus = order.getUserStatus();
        vh.noti_detail.setVisibility(View.VISIBLE);
        if(status == 0){
            // 商家未接单,那么只有详细信息按钮可以显示
            vh.orderStatus.setText("商家未接单");
        }else {
            // 查看骑手的状态了
            status = order.getRiderStatus();
            switch (status){
                case 0:
                    // 骑手未接单
                    vh.orderStatus.setText("商家已接单");
                    break;
                case 1:
                    // 骑手已接单
                    vh.orderStatus.setText("骑手已接单");
                    break;
                case 2:
                    // 骑手配送中
                    vh.orderStatus.setText("骑手配送中");
                    break;
                case 3:
                    // 骑手配送完毕 查看用户的状态了
                    if(userStatus == 1){
                        // 用户还未取到货
                        vh.orderStatus.setText("骑手已送达");
                        vh.noti_ack.setVisibility(View.VISIBLE);

                    }else if(userStatus == 2){
                        // 用户已取到货
                        vh.orderStatus.setText("订单结束");
                        vh.noti_pinjia.setVisibility(View.VISIBLE);
                    }else{
                        // 用于已评价
                        vh.orderStatus.setText("订单结束");
                    }
            }
        }

    }

    public class  ViewHolder{
        /*TextView noti_orderId;*/
        TextView noti_storeName;
        TextView noti_orderStartTime;
        TextView Da_orderEndTime;
        TextView noti_remark;
        TextView noti_totalPrice;
        Button noti_detail;
        Button noti_pinjia;
        Button noti_ack;
        TextView orderStatus;
        public ViewHolder(View view){
            /*noti_orderId = view.findViewById(R.id.noti_orderId);*/
            noti_storeName = view.findViewById(R.id.noti_storeName);
            noti_orderStartTime = view.findViewById(R.id.noti_orderStartTime);
            Da_orderEndTime = view.findViewById(R.id.Da_orderEndTime);
            noti_remark = view.findViewById(R.id.noti_remark);
            noti_totalPrice = view.findViewById(R.id.noti_totalPrice);
            noti_detail = view.findViewById(R.id.noti_detail);
            noti_pinjia = view.findViewById(R.id.noti_pinjia);
            orderStatus = view.findViewById(R.id.orderStatus);
            noti_ack = view.findViewById(R.id.noti_ack);

        }

    }
}
